use crate::errors::MyError;
use crate::models::{CodeSource, GenCodeResult, LoginResult, LoginWithPwd, Res, User, UserInit};
use crate::services;
use actix_web::{get, post, put, web::Data, web::Json, HttpResponse};
// use crate::services::{delete_note, get_note, get_notes, insert_or_update_note};
use deadpool_postgres::Pool;
use redis::Connection;
use redis_pool::SingleRedisPool;
use std::result::Result;

// 创建User
#[post("/register")]
pub async fn init_user(
    user: Json<UserInit>,
    pg_pool: Data<Pool>,
    redis_pool: Data<SingleRedisPool>,
) -> Result<Json<Res<User>>, MyError> {
    let conn: &mut Connection = &mut redis_pool.factory().get_connection()?;
    Ok(Json(Res::new(
        services::init_user(&user.into_inner(), &pg_pool.get().await?, conn).await?,
    )))
}

// 修改User
#[put("/auth/user")]
pub async fn update_user_info(
    user: Json<User>,
    pg_pool: Data<Pool>,
) -> Result<Json<Res<User>>, MyError> {
    Ok(Json(Res::new(
        services::update_user_info(&user.into_inner(), &pg_pool.get().await?).await?,
    )))
}

// 登录
#[post("/login")]
pub async fn login(
    login: Json<LoginWithPwd>,
    pg_pool: Data<Pool>,
    redis_pool: Data<SingleRedisPool>,
) -> Result<Json<Res<LoginResult>>, MyError> {
    let conn: &mut Connection = &mut redis_pool.factory().get_connection()?;
    Ok(Json(Res::new(
        services::login(&login, &pg_pool.get().await?, conn).await?,
    )))
}

//生成source
#[get("/gen_code_source")]
pub async fn gen_code_source(
    redis_pool: Data<SingleRedisPool>,
) -> Result<Json<Res<String>>, MyError> {
    let conn: &mut Connection = &mut redis_pool.factory().get_connection()?;
    Ok(Json(Res::new(services::gen_code_source(conn)?)))
}

// 生成验证码
#[post("/gen_code")]
pub async fn gen_code(
    code_source: Json<CodeSource>,
    redis_pool: Data<SingleRedisPool>,
) -> Result<Json<Res<GenCodeResult>>, MyError> {
    let conn: &mut Connection = &mut redis_pool.factory().get_connection()?;

    Ok(Json(Res::new(services::gen_img_code(
        &code_source.code,
        conn,
    )?)))
}
